package com.aceleeyy.apb.base;

import com.aceleeyy.apb.utils.ApbUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.List;

@Slf4j
public class BaseService<M extends BaseMapper<T>, T extends BaseModel> extends ServiceImpl<M, T> implements IBaseService<T> {

    @Override
    public Object list(Boolean isPage, String attributes, String filter, String orderBy, Integer skip, Integer top) {
        String whereSql = ApbUtils.parseFilters(filter);
        log.info("列表查询-条件SQL为：{}",whereSql);

        if (null!=isPage && isPage){
            return page(attributes, orderBy, skip, top, whereSql);
        }else {
            return list(attributes, orderBy, whereSql);
        }

    }

    private List<T> list(String attributes, String orderBy, String whereSql) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(attributes)) {
            String[] attrs = ApbUtils.humpToLine(attributes).split(",");
            wrapper.select(attrs);
        }
        String last = "";
        if (StringUtils.isNotBlank(whereSql)) {
            last = "and " + whereSql;
        }
        if (StringUtils.isNotBlank(orderBy)) {
            last += " order by " + ApbUtils.humpToLine(orderBy) + " ";
        }
        wrapper.last(last);
        List<T> list = list(wrapper);
        return list;
    }

    private Page<T> page(String attributes, String orderBy, Integer skip, Integer top, String whereSql) {
        Page<T> page = Page.empty();

        QueryWrapper<T> wrapper = new QueryWrapper<>();
        String last = "";
        if (StringUtils.isNotBlank(whereSql)) {
            last = "and " + whereSql;
        }
        wrapper.last(last);
        page.setTotal(count(wrapper));

        wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(attributes)) {
            String[] attrs = ApbUtils.humpToLine(attributes).split(",");
            wrapper.select(attrs);
        }
        if (StringUtils.isNotBlank(orderBy)) {
            last += " order by " + ApbUtils.humpToLine(orderBy) + " ";
        }
        int start = null==skip?0:skip;
        int end = null==top?10:top;
        last += " limit " + start + "," + end;
        wrapper.last(last);
        page.setList(list(wrapper));
        return page;
    }


}